import os
from common.enum import MyEnum


class BaseAct(object):

    def __init__(self, env, config, mode):
        self.env = env
        self.config = config
        self.mode = mode

    def add_repo(self):
        raise NotImplementedError

    def install_software(self):
        raise NotImplementedError

    def clean_repo(self):
        raise NotImplementedError

    def write_bash(self, user_home):
        bash_path = user_home + "/.bashrc"
        if not os.path.exists(bash_path):
            os.system("touch "+bash_path)
        alias = self.config.bash_alias
        cmd = self.config.bash_cmd
        with open(bash_path, "r+") as f:
            lines = f.read()
            for k, v in alias.items():
                    c = "alias %s='%s'" % (k, v)
                    c = self.parse_cmd(c)
                    if c not in lines:
                        f.write(c+"\n")
            for c in cmd:
                c = self.parse_cmd(c)
                if c not in lines:
                    f.write(c+"\n")

    def execute_cmd(self, cmd):
        if not isinstance(cmd, list):
            cmd = [cmd]
        for c in cmd:
            c = self.parse_cmd(c)
            os.system(c)

    def parse_cmd(self, cmd):
        args = dict()
        for k, v in self.env.items():
            parse_key = "{%s}" % k
            if parse_key in cmd:
                args[k] = v
        if len(args) == 0:
            return cmd
        return cmd.format(**args)

    def add_pip_index(self):
        user_home = self.env[MyEnum.user_home.value]
        pip_index = self.env[MyEnum.pip_index.value]
        conf_path = "%s/.conf/pip" % user_home
        pip_path = conf_path+"/pip.conf"
        if not os.path.exists(conf_path):
            os.makedirs(conf_path, 755)
        if not os.path.exists(pip_path):
            os.system("touch "+pip_path)
        cmd = "echo -e '[global]\nindex-url = %s' > %s" % (pip_index, pip_path)
        os.system(cmd)
        # self.change_own("%s/.conf" % user_home)

    # def change_own(self, base_dir):
    #     user_name = self.env[MyEnum.user_name.value]
    #     os.system("chown -R %s %s" % (user_name, base_dir))

    def install_py_module(self, requirement):
        pip_index = self.env[MyEnum.pip_index.value]
        if pip_index is None:
            os.system('sudo pip3 install -r %s ' % requirement)
        else:
            os.system('sudo pip3 install -r %s -i %s' % (requirement, pip_index))
